package people.paper.tv.activity.home.modual.ywyl.view.impl;

import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.NewRecycleAdapter;
import android.support.v7.widget.NewRecyclerView;
import android.support.v7.widget.OrientationHelper;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;

import com.skyworth.ui.api.SkyWithBGLoadingView;
import com.skyworth.ui.newrecycleview.NewRecycleAdapterItem;
import com.skyworth.ui.newrecycleview.NewRecycleLayout;
import com.skyworth.ui.newrecycleview.OnBoundaryListener;
import com.skyworth.ui.newrecycleview.OnItemClickListener;
import com.skyworth.ui.newrecycleview.OnItemFocusChangeListener;
import com.skyworth.ui.newrecycleview.OnScrollStateListener;
import com.skyworth.util.UiCompat;
import com.skyworth.util.Util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import people.paper.tv.activity.home.modual.ywyl.view.data.NewsData;
import people.paper.tv.utils.ui.ServerErrorLayout;

public class FocusNewsViewLayout extends FrameLayout implements OnBoundaryListener,
        OnScrollStateListener, OnItemFocusChangeListener, OnItemClickListener {
    NewRecycleLayout gridView;
    final String TAG = "YWYLViewImpl";
    List<NewsData> gridDatas;
    NewRecycleAdapter gridAdapter;
    IViewCallBack callBack;
    int curPage = -1;
    FrameLayout contentLayout;
    SparseArray<List<NewsData>> newsSparse;
    SkyWithBGLoadingView loadingView;
    ServerErrorLayout serverErrorLayout;

    public FocusNewsViewLayout(@NonNull Context context) {
        super(context);
        contentLayout = new FrameLayout(context);
        addView(contentLayout, new LayoutParams(Util.Div(1920), Util.Div(1080)));
        newsSparse = new SparseArray<>();
        showLoading();
    }

    public boolean changeFocus(boolean isLeft) {
        if(gridView != null && gridView.getChildItemCount() > 0){
            if(isLeft){
                View view = gridView.getViewByPosition(gridView.getFirstVisiblePosition());
                if(view != null){
                    view.requestFocus();
                    return true;
                }
            }else {
                int last = gridView.getFirstVisiblePosition()+3;
                View view = gridView.getViewByPosition(last);
                if(view != null){
                    view.requestFocus();
                    return true;
                }
                else {
                    View view1 = gridView.getViewByPosition(gridView.getLastVisiblePosition());
                    if(view1 != null){
                        view1.requestFocus();
                        return true;
                    }
                }
            }
        }else{
            if(serverErrorLayout != null && serverErrorLayout.getVisibility() == VISIBLE){
                serverErrorLayout.setFocus();
                return true;
            }
        }
        return false;
    }

    public void setIViewCallBack(IViewCallBack view){
        callBack = view;
    }

    private void createNewsList() {
        FrameLayout layout = new FrameLayout(getContext());
        LayoutParams params = new LayoutParams(Util.Div(1920), Util.Div(1080));
        params.leftMargin = Util.Div(87-30);
        params.topMargin = Util.Div(160-35);
        layout.setClipChildren(false);
        layout.setClipToPadding(false);
        contentLayout.addView(layout, params);
        gridView = new NewRecycleLayout(getContext(), 4, OrientationHelper.VERTICAL);
        FrameLayout.LayoutParams gridViewParams = new FrameLayout.LayoutParams(Util.Div(1800), Util.Div(900));
//        gridViewParams.leftMargin = Util.Div(- 30);
        gridViewParams.topMargin = Util.Div(5);
        gridView.setItemSpace(Util.Div(30), Util.Div(30));
        layout.addView(gridView, gridViewParams);
        gridView.setMiddleScroll(true);
        gridView.setmBoundaryListener(this);
        gridView.setmScrollStateListener(this);
        gridView.setmItemFocusChangeListener(this);
        gridView.setmItemClickListener(this);
        gridView.setClipChildren(false);
        gridView.setClipToPadding(false);
    }

    public void refresh(int pageIndex, List<NewsData> datas) {
        if (datas == null || datas.size() == 0) {
            curPage = -1;
        } else {
            if(pageIndex == 0)
                hideLoading();
            curPage = pageIndex;
            newsSparse.put(curPage, datas);
            if (gridView == null) {
                createNewsList();
            }
            if (gridDatas == null) {
                setAdapter(datas);
            } else {
                updateUI(datas);
            }
        }
    }

    protected void setAdapter(List<NewsData> datas) {
        if (datas == null || datas.size() <= 0)
            return;
        gridDatas = new ArrayList<>();
        int size = datas.size();
        for (int i = 0; i < size; i++) {
            gridDatas.add(datas.get(i));
        }
        gridAdapter = new NewRecycleAdapter<NewsData>(gridDatas, 1) {
            @Override
            public NewRecycleAdapterItem<NewsData> onCreateItem(Object type) {
                return new FocusNewsItemView(getContext());
            }
        };
        gridView.setRecyclerAdapter(gridAdapter);
//        gridView.post(new Runnable() {
//            @Override
//            public void run() {
//                if(gridView.getChildAt(0) != null) {
//                    gridView.getChildAt(0).requestFocus();
//                }
//            }
//        });
    }

    public boolean setLayoutFocus(){
        if(serverErrorLayout != null && serverErrorLayout.getVisibility() == VISIBLE){
            serverErrorLayout.setFocus();
            return true;
        }else if(gridDatas != null && gridDatas.size() > 0 && gridView != null && gridView.getChildItemCount() > 0){
            int firstVisible = gridView.getFirstVisiblePosition();
            int lastVisible = gridView.getLastVisiblePosition();
            int curFocus = firstVisible;
            if(lastVisible - firstVisible != 7){
                curFocus = firstVisible + 4;
            }
            gridView.getItemByPosition(curFocus).requestFocus();
            return true;
        }
        return false;
    }

    public void updateUI(List<NewsData> newItems) {
        int startPosition = gridDatas.size();
        gridDatas.addAll(newItems);
        if (gridView != null) {
            int itemCount = gridDatas.size();
            gridView.notifyItemRangeInserted(startPosition, itemCount);
        }
    }

    public void showLoading() {
        if (loadingView == null) {
            loadingView = new SkyWithBGLoadingView(getContext());
            contentLayout.addView(loadingView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        }
        loadingView.setVisibility(View.VISIBLE);
        loadingView.showLoading();
        loadingView.bringToFront();
        if (loadingView.getParent() != null)
            loadingView.getParent().requestLayout();
    }

    public void hideLoading() {
        if (loadingView != null) {
            loadingView.dismissLoading();
            contentLayout.removeView(loadingView);
            loadingView = null;
        }
    }

    public void showError() {
        if(curPage >= 0)
            return;
        if (serverErrorLayout == null) {
            serverErrorLayout = new ServerErrorLayout(getContext(), reloadCallback);
            contentLayout.addView(serverErrorLayout, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        }
        serverErrorLayout.setVisibility(View.VISIBLE);
        serverErrorLayout.bringToFront();
        if (serverErrorLayout.getParent() != null)
            serverErrorLayout.getParent().requestLayout();
    }

    public void hideError() {
        if (serverErrorLayout != null) {
            contentLayout.removeView(serverErrorLayout);
            serverErrorLayout = null;
        }
    }

    ServerErrorLayout.ReloadCallback reloadCallback = new ServerErrorLayout.ReloadCallback() {
        @Override
        public void reload() {
            callBack.changeFocus();
            hideError();
            showLoading();
            callBack.getNextPageData(-1);
        }

        @Override
        public boolean onkeyListener(View v, int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
                    callBack.preFragment();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
                    callBack.nextFragment();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
                    callBack.changeFocus();
                    return true;
                }else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                    return true;
                }
            }
            return false;
        }
    };

    @Override
    public boolean onLeftBoundary(View view, int i) {
        callBack.preFragment();
        return true;
    }

    @Override
    public boolean onTopBoundary(View view, int i) {
        callBack.changeFocus();
        return true;
    }

    @Override
    public boolean onDownBoundary(View view, int i) {
        return true;
    }

    @Override
    public boolean onRightBoundary(View view, int i) {
        //翻下一页
        callBack.nextFragment();
        return true;
    }

    @Override
    public boolean onOtherKeyEvent(View view, int i, int i1) {
        return false;
    }

    @Override
    public void onScrollby(int i) {

    }

    @Override
    public void onScrollStart() {

    }

    @Override
    public void onScrollEnd(NewRecyclerView newRecyclerView, int i, int i1) {
        if (curPage >= 0 && newsSparse.get(curPage+1) == null) {
            callBack.getNextPageData(curPage);
        }
    }

    @Override
    public void focusChange(View view, int i, boolean hasFocus) {
        FocusNewsItemView itemView = (FocusNewsItemView) view;
        itemView.onFocusChange(hasFocus);
    }

    @Override
    public void click(View v, int position) {
        FocusNewsItemView itemView = (FocusNewsItemView) v;
        itemView.onClickAction();
    }

    int REFRESH_COUNT = 12;
    public void resume() {
        if(gridView != null){
            int s = gridView.getFirstVisiblePosition();
            for (int j=s; j<REFRESH_COUNT+s; j++){
                View view1 = gridView.getViewByPosition(j);
                if(view1 != null)
                    ((FocusNewsItemView)view1).resume();
            }
        }
    }

    public void pause() {
        if(gridView != null){
            int count = gridView.getChildItemCount();
            int s = gridView.getFirstVisiblePosition();
            Log.i("tag", "focusnew layout pause:" + count + "; " +s);
            for (int j=s; j<REFRESH_COUNT+s; j++){
                View view1 = gridView.getViewByPosition(j);
                if(view1 != null)
                    ((FocusNewsItemView)view1).pause();
            }
        }
    }

    public void destroy() {
        if(gridView != null)
            gridView.onDestroy();
    }
}
